package avicit.bdp.dds.api.controller;

import avicit.bdp.common.service.dto.CommonTypeDTO;
import avicit.bdp.dds.api.service.UdfFuncService;
import avicit.bdp.dds.dao.entity.UdfFunc;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.system.impl.SystemConstant;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.rest.msg.QueryRespBean;
import avicit.platform6.core.rest.msg.ResponseMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * udf管理REST接口
 */
@RestController
@Api(tags = "udf管理REST接口")
@RequestMapping("/api/bdp/dds/udf")
public class UdfRest {

    @Autowired
    private UdfFuncService udfFuncService;

    @Autowired
    private ConvertColumnClient convertColumnClient;

    /**
     * 新增UDF
     */
    @PostMapping("/insertUDF")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", dataType = "String"),
            @ApiImplicitParam(name = "funcName", value = "函数名称", dataType = "String"),
            @ApiImplicitParam(name = "typeId", value = "分类id", dataType = "String"),
            @ApiImplicitParam(name = "className", value = "类名称", dataType = "String"),
            @ApiImplicitParam(name = "type", value = "类型", dataType = "Int"),
            @ApiImplicitParam(name = "argTypes", value = "参数名", dataType = "String"),
            @ApiImplicitParam(name = "remark", value = "备注", dataType = "String"),
            @ApiImplicitParam(name = "file", value = "文件", dataType = "MultipartFile"),
            @ApiImplicitParam(name = "projectId", value = "数据空间id", dataType = "String")
    })
    @ApiOperation(value = "新增UDF")
    public ResponseMsg<String> insertUDF(String name, String funcName, String typeId, String className, Integer type,
                                         String argTypes, String remark, MultipartFile file, String projectId) {

        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        responseMsg.setResponseBody(
                udfFuncService.insertUDF(name, funcName, typeId, className, type, argTypes, remark, file, projectId));
        return responseMsg;
    }

    /**
     * 修改UDF
     */
    @PostMapping("/updateUDF")
    @ApiOperation(value = "修改UDF")
    public ResponseMsg<String> updateUDF(@RequestBody UdfFunc udfFunc) {
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        udfFuncService.updateUDF(udfFunc);
        return responseMsg;
    }


    /**
     * 删除UDF
     */
    @ApiOperation(value = "按主键单条删除")
    @ApiImplicitParam(name = "id", value = "id", dataType = "String",  paramType = "body", required = true)
    @PostMapping("/deleteUDF")
    public ResponseMsg<Integer> deleteUDF(@ApiIgnore @RequestBody Map<String, String> queryMap) {
        ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
        udfFuncService.deleteUDF(queryMap.get("id"));
        return responseMsg;
    }

    /**
     * 判断资源名称是否重复
     */
    @ApiOperation(value = "判断UDF资源名称是否重复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "String",  paramType = "body"),
            @ApiImplicitParam(name = "name", value = "名称", dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "projectId", value = "数据空间id", dataType = "String", paramType = "body")
    })
    @PostMapping("/isSameName")
    public ResponseMsg<Boolean> isSameName(@ApiIgnore @RequestBody Map<String, String> queryMap) {
        ResponseMsg<Boolean> responseMsg = new ResponseMsg<>();
        String id = MapUtils.getString(queryMap, "id", "");
        String name = MapUtils.getString(queryMap, "name", "");
        String projectId = MapUtils.getString(queryMap, "projectId", "");
        Boolean flag = udfFuncService.isSameName(id, name, projectId);
        responseMsg.setResponseBody(flag);
        return responseMsg;
    }

    /**
     * 判断函数名称是否重复
     */
    @ApiOperation(value = "判断函数名称是否重复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "String",  paramType = "body"),
            @ApiImplicitParam(name = "funcName", value = "函数名称", dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "projectId", value = "数据空间id", dataType = "String", paramType = "body")
    })
    @PostMapping("/isSameFuncName")
    public ResponseMsg<Boolean> isSameFuncName(@ApiIgnore @RequestBody Map<String, String> queryMap) {
        ResponseMsg<Boolean> responseMsg = new ResponseMsg<>();
        String id = MapUtils.getString(queryMap, "id", "");
        String funcName = MapUtils.getString(queryMap, "funcName", "");
        String projectId = MapUtils.getString(queryMap, "projectId", "");
        Boolean flag = udfFuncService.isSameFuncName(id, funcName, projectId);
        responseMsg.setResponseBody(flag);
        return responseMsg;
    }

    /**
     * 查询右侧udf函数数据
     */
    @ApiOperation(value = "查询右侧数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "typeId", value = "分类id", dataType = "String"),
            @ApiImplicitParam(name = "projectId", value = "数据空间id", dataType = "String"),
            @ApiImplicitParam(name = "keyWords", value = "查询关键字", dataType = "String"),
            @ApiImplicitParam(name = "pageNo", value = "当前页", dataType = "Int"),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", dataType = "Int")
    })
    @GetMapping("/getList")
    public ResponseMsg<QueryRespBean<UdfFunc>> getList(
            @RequestParam String typeId,
            @RequestParam String projectId,
            @RequestParam(required = false) String keyWords,
            @RequestParam(defaultValue = "1", required = false) Integer pageNo,
            @RequestParam(defaultValue = "10", required = false) Integer pageSize) {
        ResponseMsg<QueryRespBean<UdfFunc>> responseMsg = new ResponseMsg<>();
        QueryRespBean<UdfFunc> result = udfFuncService.getList(typeId, projectId, keyWords, pageNo, pageSize);
        valueConvert(result.getResult());
        responseMsg.setResponseBody(result);
        return responseMsg;
    }

    /**
     * 查询UDF分类树
     */
    @ApiOperation(value = "查询UDF分类树")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "数据空间id", dataType = "String"),
            @ApiImplicitParam(name = "type", value = "分类类型", dataType = "Int")
    })
    @GetMapping(value = "/getTypeAndUdfFuncList")
    public ResponseMsg<List<CommonTypeDTO>> getTypeAndUdfFuncList(@RequestParam(value = "projectId") String projectId,
                                                                  @RequestParam(value = "type") Integer type) {
        if (StringUtils.isBlank(projectId) || type == null) {
            throw new BusinessException("参数不能为空");
        }
        ResponseMsg<List<CommonTypeDTO>> responseMsg = new ResponseMsg<>();
        responseMsg.setResponseBody(udfFuncService.getTypeAndUdfFuncList(projectId, type));
        return responseMsg;
    }

    /**
     * 通过平台API将字段值转换为名称，包括通用选择组件、通用代码
     *
     * @param udfFunList udfFunList
     */
    private void valueConvert(List<UdfFunc> udfFunList) {
        //循环组装请求数据
        Map<String, Set<String>> convertFormData = new HashMap<>();
        for (UdfFunc udfFunc : udfFunList) {
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, udfFunc.getCreatedBy());
        }
        if (convertFormData.size() > 0) {
            //获取请求结果
            Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
            //循环设置Alias或Name的值
            for (UdfFunc udfFunc : udfFunList) {
                udfFunc.setUsername(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER,
                        udfFunc.getCreatedBy()));
            }
        }
    }
}
